<template>
  <scroll-view class="flex-col page mine" scroll-y @scroll="onPageScroll">
    <view class="flex-col section" :style="{ paddingTop: navHeight + 'px' }">
      <xlm-top-nav :scrollTop="scrollTop" :title="isReadonly ? '运动员详情' : '添加运动员'" />
      <uv-form class="form-container" labelPosition="top" :model="playerForm" ref="refForm" labelWidth="250rpx">
        <!-- 上传照片 -->
        <uv-form-item label="上传照片" prop="pics" required>
          <view class="upload-desc">照片仅用于赛事查验，不收集人脸照数据</view>
          <uv-upload :fileList="fileList" name="pics" multiple :maxCount="1" @afterRead="afterRead" @delete="deletePic"
            :previewFullImage="true" :disabled="isReadonly" style="width:100%;height: 100%;">
            <template #default>
              <view class="upload-btn" v-if="!isReadonly || fileList.length === 0">
                <view class="camera-icon">
                  <svg width="48" height="48" viewBox="0 0 24 24" fill="currentColor">
                    <path
                      d="M12 2C6.48 2 2 6.48 2 12s4.48 10 10 10 10-4.48 10-10S17.52 2 12 2zm-2 15l-5-5 1.41-1.41L10 14.17l7.59-7.59L19 8l-9 9z" />
                  </svg>
                </view>
                <text>点击上传</text>
              </view>
            </template>
          </uv-upload>
        </uv-form-item>

        <!-- 国家/地区 -->
        <!-- <uv-form-item label="国家/地区" prop="country" required>
          <uv-input v-model="playerForm.country" border="none" readonly placeholder="请选择" />
        </uv-form-item> -->

        <!-- 省市区 -->
        <uv-form-item class="form-item" label="省市区" prop="region" required>
          <!-- 只读模式：直接显示region文本 -->
          <template v-if="isReadonly">
            <uv-input v-model="playerForm.region" disabled border="none" placeholder="请选择省市区" />
          </template>
          <!-- 编辑模式：使用AreaPicker -->
          <template v-else>
            <view class="input" style="border:1rpx solid #dadbde;height: 72rpx;">
              <area-picker :placeholder="'请选择省市区'" :arrow-icon="imgUrl + 'arrow-right.png'"
                :disabled="false"
                :default-value="{ province: playerForm.province_id, city: playerForm.city_id, district: playerForm.region_id }"
                @change="onAreaChange" @cancel="onAreaCancel" />
            </view>
          </template>
        </uv-form-item>

        <!-- 真实姓名 -->
        <uv-form-item label="真实姓名" prop="username" required>
          <uv-input v-model="playerForm.username" :disabled="isReadonly" border="none" placeholder="请输入" />
        </uv-form-item>

        <!-- 证件类型 -->
        <uv-form-item label="证件类型" prop="type" required>
          <picker mode="selector" :range="idTypeOptions" range-key="label" @change="onIdTypeChange" :disabled="isReadonly">
            <view class="picker-input" :class="{ 'picker-disabled': isReadonly }">
              <text class="picker-text" :class="{ 'placeholder': !playerForm.type }">
                {{ getSelectedIdTypeLabel() || '请选择证件类型' }}
              </text>
              <image :src="imgUrl + 'arrow-right.png'" class="picker-arrow" v-if="!isReadonly" />
            </view>
          </picker>
        </uv-form-item>

        <!-- 证件号 -->
        <uv-form-item label="证件号" prop="idcard" required>
          <uv-input v-model="playerForm.idcard" :disabled="isReadonly" border="none" placeholder="请输入" />
        </uv-form-item>


        <!-- 学校 -->
        <uv-form-item label="学校" prop="school" required>
          <uv-input v-model="playerForm.school" :disabled="isReadonly" border="none" placeholder="请输入学校名称" />
        </uv-form-item>

        <!-- 年级 -->
        <uv-form-item label="年级" prop="grade" required>
          <!-- <uv-input v-model="playerForm.grade" border="none" placeholder="请输入年级" /> -->
          <picker mode="selector" :range="gradeOptions" range-key="label" @change="onGradeChange" :disabled="isReadonly">
            <view class="picker-input" :class="{ 'picker-disabled': isReadonly }">
              <text class="picker-text" :class="{ 'placeholder': !playerForm.grade }">
                {{ getSelectedGradeLabel() || '请选择年级' }}
              </text>
              <image :src="imgUrl + 'arrow-right.png'" class="picker-arrow" v-if="!isReadonly" />
            </view>
          </picker>
        </uv-form-item>

        <!-- 性别 -->
        <uv-form-item label="性别" prop="gender" required>
          <picker mode="selector" :range="genderOptions" range-key="label" @change="onGenderChange" :disabled="isReadonly">
            <view class="picker-input" :class="{ 'picker-disabled': isReadonly }">
              <text class="picker-text" :class="{ 'placeholder': !playerForm.gender }">
                {{ getSelectedGenderLabel() || '请选择性别' }}
              </text>
              <image :src="imgUrl + 'arrow-right.png'" class="picker-arrow" v-if="!isReadonly" />
            </view>
          </picker>
        </uv-form-item>


        <!-- Email -->
        <uv-form-item label="Email" prop="email" required>
          <uv-input v-model="playerForm.email" :disabled="isReadonly" border="none" placeholder="请输入" />
        </uv-form-item>

        <!-- 手机号 -->
        <uv-form-item label="手机号" prop="mobile" required>
          <uv-input v-model="playerForm.mobile" :disabled="isReadonly" border="none" placeholder="请输入" />
        </uv-form-item>
        <!-- 验证码 -->
        <!-- 验证码输入区域 -->
        <uv-form-item label="验证码" prop="captcha" required v-if="!isReadonly">
          <view class="verify-row">
            <uv-input v-model="playerForm.captcha" border="none" placeholder="请输入" class="verify-input" />
            <button class="get-code-btn" :disabled="countdownActive" @click="getVerificationCode" type="default">
              {{ countdownActive ? `${countdown}s后重发` : '获取验证码' }}
            </button>
          </view>
        </uv-form-item>
      </uv-form>
      <!-- 协议勾选区域 -->
      <view class="agreement-section" v-if="!isReadonly">
        <view class="agreement-item">
          <view class="checkbox" :class="{ checked: agreed }" @tap="toggleAgreement">
            <text v-if="agreed" class="checkmark">✓</text>
          </view>
          <view class="agreement-text">
            <text @tap="toggleAgreement">我已阅读并同意</text>
            <text class="link" @tap="showAgreementPopup">《用户服务协议》</text>
            <text @tap="toggleAgreement">和</text>
            <text class="link" @tap="showPrivacyPopup">《用户隐私》</text>
            <text @tap="toggleAgreement">，并授权个人信息用于草源体育公开赛事助手报名</text>
          </view>
        </view>
      </view>
      <!-- <button class="mt-24 flex-col justify-start items-center text-wrapper w-full" @click="submitForm">
        <text class="text">保存参赛信息</text>
      </button> -->
      <view class="footer-bar" v-if="!isReadonly">
        <view class="footer-home" @click="goHome">
          <image :src="imgUrl + 'home@2x.png'" class="home-icon" />
          <text class="home-text">首页</text>
        </view>
        <button class="save-btn" @click="submitForm">
          保存参赛信息
        </button>
      </view>
      <!-- 只读模式显示返回按钮 -->
      <!-- <view class="footer-bar readonly-footer" v-else>
        <button class="back-btn" @click="goBack">
          返回
        </button>
      </view> -->
    </view>

    <!-- 用户服务协议弹出层 -->
    <uni-popup ref="agreementPopup" type="bottom" :safe-area="true">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">用户服务协议</text>
          <view class="close-btn" @tap="closeAgreementPopup">
            <text class="close-icon">×</text>
          </view>
        </view>
        <scroll-view class="popup-body" scroll-y="true">
          <view v-if="loading" class="loading-content">
            <text>加载中...</text>
          </view>
          <view v-else-if="error" class="error-content">
            <text>{{ error }}</text>
            <button @tap="getServiceAgreement" class="retry-btn">重试</button>
          </view>
          <MpHtmlWrapper v-else :content="htmlContent" :max-length="8000" @load="onMpHtmlLoad('useragreement')"
            @error="onMpHtmlError('useragreement')" />
        </scroll-view>
      </view>
    </uni-popup>

    <!-- 用户隐私弹出层 -->
    <uni-popup ref="privacyPopup" type="bottom" :safe-area="true">
      <view class="popup-content">
        <view class="popup-header">
          <text class="popup-title">用户隐私</text>
          <view class="close-btn" @tap="closePrivacyPopup">
            <text class="close-icon">×</text>
          </view>
        </view>
        <scroll-view class="popup-body" scroll-y="true">
          <view v-if="loading" class="loading-content">
            <text>加载中...</text>
          </view>
          <view v-else-if="error" class="error-content">
            <text>{{ error }}</text>
            <button @tap="getPrivacyPopup" class="retry-btn">重试</button>
          </view>
          <MpHtmlWrapper v-else :content="privacyContent" :max-length="8000" @load="onMpHtmlLoad('privacyagreement')"
            @error="onMpHtmlError('privacyagreement')" />
        </scroll-view>
      </view>
    </uni-popup>

  </scroll-view>
</template>

<script setup>
import { ref, computed, nextTick } from 'vue'
import { useOutsideAppStore } from '@/store/app'
import { imgUrl } from '@/utils/config'
import AreaPicker from '@/components/AreaPicker/index.vue'
import { onShow, onLoad } from '@dcloudio/uni-app';
import { useRequest } from '@/api'
import MpHtmlWrapper from '@/components/MpHtmlWrapper/MpHtmlWrapper.vue'
import { useRouter } from 'vue-router'
const router = useRouter()
const appStore = useOutsideAppStore()
const navHeight = computed(() => appStore.navHeight)
const scrollTop = ref(0)
const onPageScroll = (e) => {
  scrollTop.value = e.detail.scrollTop
}
const { API_INDEX_UPLOAD_POST, API_SMS_SENDATHLETE_POST, API_MEMBER_ADDATHLETE_POST, API_GET_PRIVACY_AGREEMENT, API_GET_SERVICE_AGREEMENT, API_MEMBER_LISTATHLETE_POST } = useRequest()
const fileList = ref([])
const isReadonly = ref(false)
const athleteId = ref('')
const playerForm = ref({
  pics: [],
  avatar: '', // 头像地址
  country: 'CHINA 中国',
  region: '',
  address: '', // 地址
  // 地区 id
  province_id: '', // 省
  city_id: '', // 市
  region_id: '', // 区
  username: '', // 真实姓名
  type: 'idcard', // 证件类型 - 默认选择身份证
  idcard: '', // 证件号
  email: '', // 邮箱
  mobile: '', // 手机号
  captcha: '', // 验证码
  school: '', // 学校
  grade: '', // 年级
  gender: '' // 性别
})
const genderOptions = ref([
  {
    label: '未知',
    value: 0
  },
  {
    label: '男',
    value: 1
  },
  {
    label: '女',
    value: 2
  }
])
const afterRead = async (e) => {
  const file = Array.isArray(e.file) ? e.file[0] : e.file
  console.log('file', file);

  if (!file) return
  try {
    uni.showLoading({ title: '上传中...' })

    // 使用 uni.uploadFile 进行文件上传
    const res = await new Promise((resolve, reject) => {
      uni.uploadFile({
        // url: '/api/index/upload',
        url: `${import.meta.env.VITE_APP_API_BASEURL}/api/index/upload`,
        filePath: file.url || file.path,
        name: 'file',
        header: {
          Authorization: uni.getStorageSync('token')
        },
        success: (uploadRes) => {
          try {
            const data = JSON.parse(uploadRes.data)
            resolve(data)
          } catch (e) {
            resolve(uploadRes)
          }
        },
        fail: (error) => {
          reject(error)
        }
      })
    })

    console.log('API_INDEX_UPLOAD_POSTres', res);

    // 期望后端返回 { code:1, data: { url: 'xxx' } }
    if (res && res.code === 1) {
      const url = res.data?.fullurl
      fileList.value = [{ url }]
      // 正确设置 pics 字段
      playerForm.value.pics = [url]; // 直接设置为 URL 数组
      playerForm.value.avatar = url;
      console.log('上传成功，设置 pics:', playerForm.value.pics);
    } else {
      uni.showToast({ title: res?.msg || '上传失败', icon: 'none' })
    }
  } catch (err) {
    console.error('上传失败:', err)
    uni.showToast({ title: '上传失败', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}
const deletePic = (e) => {
  fileList.value.splice(e.index, 1)
  // 同步更新 playerForm 中的 pics 字段
  playerForm.value.pics = fileList.value.map(item => item.url);
  console.log('删除照片后，pics:', playerForm.value.pics);
}

const countdownActive = ref(false)
const countdown = ref(60)
const agreed = ref(false) // 协议勾选状态
const agreementPopup = ref(null)
const privacyPopup = ref(null)
const htmlContent = ref('')
const privacyContent = ref('')
const loading = ref(false)
const error = ref('')
// 控制手机号提示只在页面首次展示
const hasShownMobileTip = ref(false)
// 省市区选择器事件处理
function onAreaChange(areaData) {
  if (!areaData) return
  // 显示文本
  playerForm.value.region = areaData.areaText
  playerForm.value.address = (areaData.areaText || '').replace(/\s+/g, '')
  // 后端所需的 id
  playerForm.value.province_id = areaData.province_id
  playerForm.value.city_id = areaData.city_id
  playerForm.value.region_id = areaData.region_id
}

function onAreaCancel() {
  console.log('地区选择取消')
}
const getVerificationCode = async () => {
  if (countdownActive.value) return
  const mobile = playerForm.value.mobile
  if (!/^1\d{10}$/.test(mobile || '')) {
    uni.showToast({ title: '请输入正确手机号', icon: 'none' })
    return
  }
  const ok = await sendVerificationCode()
  if (!ok) return
  // 启动倒计时（仅在发送成功后）
  countdownActive.value = true
  countdown.value = 60
  const timer = setInterval(() => {
    countdown.value--
    if (countdown.value <= 0) {
      clearInterval(timer)
      countdownActive.value = false
    }
  }, 1000)
}
const sendVerificationCode = async () => {
  let params = {
    mobile: playerForm.value.mobile,
    // event: 'register' // register 注册  ; resetpwd 重置密码 ;changepwd 修改密码;profile 修改个人资料;notice 暂未使用;mobilelogin 手机号登录;bind 绑定账号
  }
  try {
    const res = await API_SMS_SENDATHLETE_POST(params)
    console.log('API_SMS_SENDATHLETE_POSTres', res);
    if (res && res.code === 1) {
      uni.showToast({ title: '发送成功', icon: 'success' })
      return true
    }
    uni.showToast({ title: res?.msg || '发送失败', icon: 'none' })
    return false
  } catch (err) {
    uni.showToast({ title: '发送失败', icon: 'none' })
    return false
  }
}

const idTypeOptions = ref([
  {
    label: '身份证',
    value: 'idcard'
  },
  {
    label: '护照',
    value: 'passport'
  },

])
const gradeOptions = ref([
  {
    label: '一年级',
    value: '一年级'
  },
  {
    label: '二年级',
    value: '二年级'
  },
  {
    label: '三年级',
    value: '三年级'
  },
  {
    label: '四年级',
    value: '四年级'
  },
  {
    label: '五年级',
    value: '五年级'
  },
  {
    label: '六年级',
    value: '六年级'
  },
  {
    label: '初一',
    value: '初一'
  },
  {
    label: '初二',
    value: '初二'
  },
  {
    label: '初三',
    value: '初三'
  },
  {
    label: '高一',
    value: '高一'
  },
  {
    label: '高二',
    value: '高二'
  },
  {
    label: '高三',
    value: '高三'
  },

])
const onIdTypeChange = (e) => {
  const selectedIndex = e.detail.value;
  const selectedOption = idTypeOptions.value[selectedIndex];
  if (selectedOption) {
    playerForm.value.type = selectedOption.value;
  }
}
const onGradeChange = (e) => {
  const selectedIndex = e.detail.value;
  const selectedOption = gradeOptions.value[selectedIndex];
  if (selectedOption) {
    playerForm.value.grade = selectedOption.value;
  }
  // console.log('playerForm.value.grade',playerForm.value.grade);
}

const rules = ref({
  pics: [{ required: true, message: '请上传照片', trigger: 'change' }],
  // country: [{ required: true, message: '请选择国家/地区', trigger: 'blur' }],
  // region: [{ required: true, message: '请选择省市区', trigger: 'blur' }],
  // username: [{ required: true, message: '请输入真实姓名', trigger: 'blur' }],
  // type: [{ required: true, message: '请选择证件类型', trigger: 'blur' }],
  // idcard: [{ required: true, message: '请输入证件号', trigger: 'blur' }],
  // email: [
  //   { required: true, message: '请输入Email', trigger: 'blur' },
  //   { type: 'email', message: 'Email格式不正确', trigger: 'blur' }
  // ],
  // mobile: [
  //   { required: true, message: '请输入手机号', trigger: 'blur' },
  //   { pattern: /^1\d{10}$/, message: '手机号格式不正确', trigger: 'blur' }
  // ],
  // captcha: [
  //   { required: true, message: '请输入验证码', trigger: 'blur' },
  //   { pattern: /^\d{4,6}$/, message: '验证码格式不正确', trigger: 'blur' }
  // ]
})
// 协议相关函数
function toggleAgreement() {
  agreed.value = !agreed.value
}

// 显示用户服务协议弹出层
const showAgreementPopup = () => {
  if (!htmlContent.value) {
    getServiceAgreement()
  }
  agreementPopup.value.open()
}

// 关闭用户服务协议弹出层
const closeAgreementPopup = () => {
  agreementPopup.value.close()
}

// 显示用户隐私弹出层
const showPrivacyPopup = () => {
  if (!privacyContent.value) {
    getPrivacyPopup()
  }
  privacyPopup.value.open()
}

// 关闭用户隐私弹出层
const closePrivacyPopup = () => {
  privacyPopup.value.close()
}

// 获取用户服务协议
const getServiceAgreement = async () => {
  try {
    loading.value = true
    error.value = ''

    const res = await API_GET_SERVICE_AGREEMENT()
    console.log('getUserAgreement', res)

    if (res.code === 1) {
      htmlContent.value = res.data.useragreement
    } else {
      error.value = res?.msg || '获取用户服务协议失败'
      uni.showToast({ title: res?.msg || '获取用户服务协议失败', icon: 'none' })
    }
  } catch (error) {
    console.error('获取用户服务协议失败:', error)
    error.value = '网络错误'
    uni.showToast({ title: '网络错误', icon: 'none' })
  } finally {
    loading.value = false
  }
}

// 获取隐私政策
const getPrivacyPopup = async () => {
  try {
    loading.value = true
    error.value = ''

    const res = await API_GET_PRIVACY_AGREEMENT()
    console.log('getPrivacyPopup', res)

    if (res.code === 1) {
      privacyContent.value = res.data.privacyagreement
    } else {
      error.value = res?.msg || '获取隐私政策失败'
      uni.showToast({ title: res?.msg || '获取隐私政策失败', icon: 'none' })
    }
  } catch (error) {
    console.error('获取隐私政策失败:', error)
    error.value = '网络错误'
    uni.showToast({ title: '网络错误', icon: 'none' })
  } finally {
    loading.value = false
  }
}

// HTML 内容加载和错误处理
const onMpHtmlLoad = (type) => {
  if (type === 'useragreement') {
    console.log('用户协议加载成功')
  } else if (type === 'privacyagreement') {
    console.log('隐私政策加载成功')
  }
  error.value = ''
}

const onMpHtmlError = (type, err) => {
  if (type === 'useragreement') {
    console.error('用户协议渲染失败:', err)
  } else if (type === 'privacyagreement') {
    console.error('隐私政策渲染失败:', err)
  }
  error.value = '内容渲染失败，请重试'
}
const submitForm = () => {
  console.log('playerForm', playerForm.value);
  // 检查协议是否勾选
  if (!agreed.value) {
    uni.showToast({ title: '请先同意用户协议', icon: 'none' })
    return
  }

  // 手动验证所有必填字段
  const requiredFields = ['pics', 'region', 'username', 'type', 'idcard', 'email', 'mobile', 'captcha']
  const missingFields = []

  requiredFields.forEach(field => {
    const value = playerForm.value[field]
    if (!value || (Array.isArray(value) && value.length === 0)) {
      missingFields.push(field)
    }
  })

  if (missingFields.length > 0) {
    console.log('缺少必填字段:', missingFields)
    uni.showToast({ title: '请完善必填信息', icon: 'none' })
    return
  }

  // 特殊验证 pics 字段
  if (!playerForm.value.pics || playerForm.value.pics.length === 0) {
    uni.showToast({ title: '请上传照片', icon: 'none' })
    return
  }
  submitPlayerInfo(playerForm.value)
  // console.log('表单验证通过，准备提交数据:', playerForm.value)
  // uni.showToast({ title: '提交成功', icon: 'success' })

  // 这里可以添加实际的提交API调用
  // submitPlayerInfo(playerForm.value)
}
const refForm = ref(null)
const submitPlayerInfo = async (playerForm) => {
  try {

    const res = await API_MEMBER_ADDATHLETE_POST(playerForm)
    console.log('submitPlayerInfo', res)

    if (res.code === 1) {
      uni.showToast({ title: '提交成功', icon: 'success' })
      uni.navigateBack();//返回上一页
    } else {
      uni.showToast({ title: res?.msg || '提交失败', icon: 'none' })
    }
  } catch (error) {
    uni.showToast({ title: error?.message || '提交失败', icon: 'none' })
  }
}
const goHome = () => {
  uni.navigateTo({
    url: '/pages/leagueMatchesHome/index'
  })
}

const goBack = () => {
  uni.navigateBack()
}

// 页面加载时处理参数
onLoad((options) => {
  console.log('onLoad options', options)
  if (options.athlete_id) {
    athleteId.value = options.athlete_id
  }
  if (options.readonly === 'true') {
    isReadonly.value = true
  }
  
  // 如果是只读模式且有运动员ID，加载运动员数据
  if (isReadonly.value && athleteId.value) {
    loadAthleteData()
  }
})

// 页面显示时显示手机号提示弹窗（仅首次，非只读模式）
onShow(() => {
  if (isReadonly.value) return
  
  setTimeout(() => {
    if (hasShownMobileTip.value) return
    hasShownMobileTip.value = true
    showMobileTipModal()
  }, 500)
})

// 加载运动员数据
const loadAthleteData = async () => {
  try {
    uni.showLoading({ title: '加载中...' })
    const params = {
      page: 1,
      page_size: 100,
      lng: uni.getStorageSync('longitude'),
      lat: uni.getStorageSync('latitude')
    }
    const res = await API_MEMBER_LISTATHLETE_POST(params)
    console.log('loadAthleteData', res)
    
    if (res.code === 1 && res.data.data.length > 0) {
      const athlete = res.data.data.find(item => item.id == athleteId.value)
      if (athlete) {
        // 填充表单数据
        // 省市区：直接使用 address 字段
        const regionText = athlete.address || ''
        
        // 性别：确保是数字类型（0=未知，1=男，2=女）
        let genderValue = athlete.gender
        if (typeof genderValue !== 'number' && genderValue !== undefined && genderValue !== null) {
          // 如果gender是字符串，转换为数字
          genderValue = parseInt(genderValue)
        }
        // 如果没有gender值或转换失败，默认为0（未知）
        if (isNaN(genderValue)) {
          genderValue = 0
        }
        
        // 确保ID是数字类型
        const provinceId = Number(athlete.province_id || athlete.provinceId || 0)
        const cityId = Number(athlete.city_id || athlete.cityId || 0)
        const regionId = Number(athlete.region_id || athlete.regionId || 0)
        
        playerForm.value = {
          pics: athlete.avatar ? [athlete.avatar] : [],
          avatar: athlete.avatar || '',
          country: 'CHINA 中国',
          region: regionText,
          address: regionText,
          province_id: provinceId,
          city_id: cityId,
          region_id: regionId,
          username: athlete.username || '',
          type: athlete.type || 'idcard',
          idcard: athlete.idcard || '',
          email: athlete.email || '',
          mobile: athlete.mobile || '',
          captcha: '',
          school: athlete.school || '',
          grade: athlete.grade || '',
          gender: genderValue
        }
        
        console.log('回显的数据:', {
          region: playerForm.value.region,
          province_id: playerForm.value.province_id,
          city_id: playerForm.value.city_id,
          region_id: playerForm.value.region_id,
          gender: playerForm.value.gender
        })
        
        // 设置文件列表
        if (athlete.avatar) {
          fileList.value = [{ url: athlete.avatar }]
        }
        
        // 只读模式下自动勾选协议
        agreed.value = true
      }
    } else {
      uni.showToast({ title: '未找到运动员信息', icon: 'none' })
    }
  } catch (error) {
    console.error('加载运动员数据失败:', error)
    uni.showToast({ title: '加载失败', icon: 'none' })
  } finally {
    uni.hideLoading()
  }
}

// 显示手机号提示弹窗
const showMobileTipModal = () => {
  uni.showModal({
    title: '重要提示',
    content: '您填写的手机号请保持与报名时录入的手机号保持一致！系统好根据手机号匹配您的比赛成绩。',
    showCancel: false,
    confirmText: '我知道了',
    confirmColor: '#007AFF'
  });
}

// 获取证件类型标签
const getSelectedIdTypeLabel = () => {
  const selectedOption = idTypeOptions.value.find(option => option.value === playerForm.value.type);
  return selectedOption ? selectedOption.label : '';
}
// 获取年级标签
const getSelectedGradeLabel = () => {
  const selectedOption = gradeOptions.value.find(option => option.value === playerForm.value.grade);
  return selectedOption ? selectedOption.label : '';
}

const onGenderChange = (e) => {
  const selectedIndex = e.detail.value;
  const selectedOption = genderOptions.value[selectedIndex];
  if (selectedOption) {
    playerForm.value.gender = selectedOption.value;
  }
}
const getSelectedGenderLabel = () => {
  const selectedOption = genderOptions.value.find(option => option.value === playerForm.value.gender);
  return selectedOption ? selectedOption.label : '';
}

</script>

<style lang="scss" scoped>
@import './index.scss';
</style>